<%@ page contentType="image/JPEG"  pageEncoding="UTF-8"%> 
<%@ page import="java.awt.Color"%>
<%@ page import="java.awt.Font"%>
<%@ page import="java.awt.Graphics"%>
<%@ page import="java.awt.image.BufferedImage"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%@ page import="java.util.Date"%>
<%@ page import="java.util.Random"%>
<%@ page import="javax.imageio.ImageIO" %>
<%@ page import="org.apache.log4j.Logger"%>
<%@ page import="com.sun.image.codec.jpeg.JPEGCodec"%>
<%@ page import="com.sun.image.codec.jpeg.JPEGImageEncoder"%>

<%!
private Random random = new Random();
//生成验证码字符串
private String getRand() {
	char   ch[]={'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
			'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
			'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    Random random   =   new   Random();
    int length = 4;
    if(length>0){
        char[] result = new char[length];
        int loops = length/5,index = 0,rand = random.nextInt();
        for(int i=0; i<length%5; i++){
            result[index++] = ch[(byte)rand&35];
            rand >>= 6;
        }
        for(int i=loops; i>0; i--){
            rand = random.nextInt();
            for(int j=0; j<5; j++){
                result[index++] = ch[(byte)rand&35];
                rand   >>=   6;
            }
        }
        return new String(result,0,length);
    }else if(length == 0){
        return "";
    }else {
        throw new IllegalArgumentException("参数为：" + length);
    }
}
private BufferedImage getImage(String srand) {
	int topmargin = 0;
	int width = 55;
	int height = 20 + topmargin;

	BufferedImage image = new BufferedImage(width, height,
			BufferedImage.TYPE_INT_RGB);
	Graphics g = image.getGraphics();
	g.setColor(Color.WHITE);
	g.fillRect(0, 0, width, height);

	g.setColor(getRandColor(220, 255, false));
	g.fillRect(0, topmargin, width, height);

	g.setFont(new Font("Arial", Font.BOLD, 20));

	for (int i = 0; i < 3; i++) {
		g.setColor(getRandColor(20, 80, true));
		int x = random.nextInt(width / 4);
		int y = random.nextInt(height - topmargin) + topmargin;
		int xl = random.nextInt(width / 4) + 3 * width / 4;
		int yl = random.nextInt(height - topmargin) + topmargin;
		g.drawLine(x, y, xl, yl);
	}
	for (int i = 0; i < 4; i++) {
		g.setColor(getRandColor(20, 80, true));
		g.drawString(srand.substring(i, i + 1), 13 * i + 3, 18 + topmargin);
	}
	g.dispose();

	return image;
}

private Color getRandColor(int fc, int bc, boolean highlight) {
	int hilight = -1;
	if (highlight)
		hilight = random.nextInt(3);
	int[] c = new int[3];
	for (int i = 0; i < 3; i++) {
		c[i] = random.nextInt(bc - fc) + fc;
		if (hilight == i) {
			c[i] += 70;
			if (c[i] > 255)
				c[i] = 255;
		}
	}
	return new Color(c[0], c[1], c[2]);
}
%>
<%
out.clear(); //tomcat可以不要，但是weblogic没有的话就不显示图像。

response.setHeader("Pragma", "No-cache");   
response.setHeader("Cache-Control", "no-cache");   
response.setDateHeader("Expires", 0);   

String srand = getRand();
request.getSession().setAttribute("attachCode", srand);


//验证码存放在数据库，以键值对方式取值 20120918
//try{
//	String currentTime = XssUtils.xssFilter(request.getParameter("currentTime"));
//	mapper acMapper = mapper.getInstance();
//	acMapper.add("attachCode"+currentTime,srand);
//	Logger.getLogger(this.getClass()).info("attachCode: " + srand + " currentTime: " + currentTime);	
//}catch(Exception e){
//	Logger.getLogger(this.getClass()).info("验证码添加出错");
//	e.printStackTrace();	
//}

SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
String sysTime = format.format(new Date());
request.getSession().setAttribute("attachCodeTime", sysTime);

Logger.getLogger(this.getClass()).info("jsp random code is " + srand);

BufferedImage image = getImage(srand);
//输出图象到页面   
//ImageIO.write(image, "JPEG", response.getOutputStream());  
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response
		.getOutputStream());
encoder.encode(image);

%>